package com.shangjinrong.controller.api;

import com.alibaba.fastjson.JSON;
import com.shangjinrong.domain.vo.UserBindVO;
import com.shangjinrong.hfb.RequestHelper;
import com.shangjinrong.result.R;
import com.shangjinrong.service.UserBindService;
import com.shangjinrong.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Naruto
 */


@RestController
@CrossOrigin
@RequestMapping("api/userBind")
@Slf4j
public class UserBindController {

    @Autowired
    private UserBindService userBindService;

    @PostMapping("bind")
    public R bind(@RequestBody UserBindVO userBindVo, HttpServletRequest request) {

        //从header中获取token，并对token校验，确保已经登录，并从token中获取UserId
        String token = request.getHeader("token");

        Long userId = JwtUtils.getUserId(token);

        String formStr = userBindService.commitBindUser(userBindVo, userId);

        return R.ok().data("formStr", formStr);
    }


    @PostMapping("notify")
    public String notify(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("账户绑定异步回调接受的参数如下：" + JSON.toJSONString(paramMap));


        //校验签名
        if (!RequestHelper.isSignEquals(paramMap)) {
            log.error("用户账号绑定异步回调签名验证错误：", JSON.toJSONString(paramMap));
            return "fail";
        }

        log.info("校验签名成功，开始账户绑定");
        userBindService.notify(paramMap);

        return "success";
    }


}
